jQuery plugin design pattern for using `this` in private methods?
Posted
by thebossman
on Stack Overflow
See other posts from Stack Overflow
or by thebossman
Published on 2010-06-05T20:47:46Z
Indexed on
2010/06/05
20:52 UTC
Read the original article
Hit count: 177
I'm creating jQuery plugins using the pattern from the Plugins Authoring page:
(function($) {
$.fn.myPlugin = function(settings) {
var config = {'foo': 'bar'};
if (settings) $.extend(config, settings);
this.each(function() {
// element-specific code here
});
return this;
};
})(jQuery);
My code calls for several private methods that manipulate this
. I am calling these private methods using the apply(this, arguments)
pattern. Is there a way of designing my plugin such that I don't have to call apply to pass this
from method to method?
My modified plugin code looks roughly like this:
(function($) {
$.fn.myPlugin = function(settings) {
var config = {'foo': 'bar'};
if (settings) $.extend(config, settings);
this.each(function() {
method1.apply(this);
});
return this;
};
function method1() {
// do stuff with $(this)
method2.apply(this);
}
function method2() {
// do stuff with $(this), etc...
}
})(jQuery);
© Stack Overflow or respective owner